package com.example.wryproject.provider;

import com.example.wryproject.ResourceTable;
import com.example.wryproject.customcomponent.AudioRateComponent;
import com.example.wryproject.database.MusicData;
import com.example.wryproject.slice.MusicAbilitySlice;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;

import java.util.List;

public class MusicListProvider extends BaseItemProvider {
    private List<MusicData> musicDataList;
    private AbilitySlice slice;
    private int position = -1;
    private boolean isPlayer;

    public MusicListProvider(List<MusicData> musicDataList, MusicAbilitySlice slice) {
        this.musicDataList = musicDataList;
        this.slice = slice;
    }

    @Override
    public int getCount() {
        return musicDataList.size();
    }

    /**
     * 刷新播放状态
     *
     * @param oldPosition 上一首歌的position
     * @param position    要播放的歌曲的position
     * @param isPlayer    是播放还是暂停
     */
    public void updatePlayerState(int oldPosition, int position, boolean isPlayer) {
        this.position = position;
        this.isPlayer = isPlayer;
        if (oldPosition != -1) {
            notifyDataSetItemChanged(oldPosition);
        }
        notifyDataSetItemChanged(position);
    }

    @Override
    public Object getItem(int i) {
        return musicDataList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return musicDataList.get(i).getMusicId();
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        final Component cpt;
        if (component == null) {
            cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_music_list_item, null, false);
        } else {
            cpt = component;
        }
        Text textTitle = (Text) cpt.findComponentById(ResourceTable.Id_text_title);
        Text textSingerName = (Text) cpt.findComponentById(ResourceTable.Id_singerName);
        AudioRateComponent audioRate = (AudioRateComponent) cpt.findComponentById(ResourceTable.Id_audio_rate);
        audioRate.setVisibility(this.position == position ? Component.VISIBLE : Component.HIDE);
        if (this.position == position) {
            audioRate.setIsRefresh(isPlayer);
        }
        String title = musicDataList.get(position).getMusicTitle();
        String singerName = musicDataList.get(position).getSinger();
        textSingerName.setText(singerName);
        textTitle.setText(title);
        return cpt;
    }
}
